import { Navigate, useLocation } from 'react-router-dom';
import RouteUtil from '@/utils/route.js';
import { routeList } from '@/router';
import { connect, useDispatch } from 'react-redux';
import { UserAction } from '@/actions/user/action.js';
import TokenUtil from '@/utils/token.js';
import StringUtil from '@/utils/string.js';

function RouteGuard(props) {
  const { pathname } = useLocation();
  const dispatch = useDispatch();
  let token = props.token;

  // 检查cookie中是否存在token
  if (StringUtil.isEmpty(token)) {
    const cookieToken = TokenUtil.getToken();
    if (StringUtil.isNotEmpty(cookieToken)) {
      dispatch(UserAction.setToken(cookieToken));
    }
  }

  // 获取当前路径对应的路由配置
  const route = RouteUtil.matchRoute(pathname, routeList);
  const isAuth = (route && route?.auth) ?? true;

  // 如果isAuth为false，则放行
  if (!isAuth) {
    // 如果是登录页并且存在token，则进入主页
    if (pathname === '/login' && token) {
      return <Navigate to="/" />;
    }
    return props.children;
  }

  // 存在token，则进入主页，否则重定向到登录页
  return token ? <>{props.children}</> : <Navigate to="/login" />;
}

const mapStateToProps = (state) => {
  return {
    token: state.user?.token
  };
};

export default connect(mapStateToProps)(RouteGuard);
